<?php
    namespace app\htapi\controller;
    use app\api\controller\Base;
    use think\Controller as Controller;
    use think\Request;

    class User extends Base
    {
        public function login(){
            if(request()->isPost()){
                $ip = Request::instance()->ip();
                $username = input('post.username');
                $password = input('post.password');
                $data = db('user')->where(['username' => $username])->find();
                if(empty($username) || empty($password)){
                    return show(0,'信息不完整，请重新输入');
                } elseif (!$data){
                    return show(0,'该用户不存在');
                } elseif ($password != $data['password']){
                    return show(0,'密码错误');
                }
                $token = $this->getToken();
                db('user')->where(['id' => $data['id']])->update(['last_login_time' => time(),'last_login_ip' => $ip,'token' => $token]);
                $loginRcord = [
                    'user_id' => $data['id'],
                    'last_login_time' => time(),
                    'last_login_ip' => $ip
                ];
                db('loginrecord')->insert($loginRcord);
                session('user', $data,'user');
                return [
                    'status' => 1,
                    'msg' => '登录成功',
                    'token' => $token
                ];
            } else{
                $this->error('请求非法');
            }
        }
        public function getToken(){
            $token = Request::instance()->token();
            return $token;
        }
        public function logout(){
            session(null,'user');
            return show(1,'退出成功');
        }
    }